using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using User.Service.Role;
using hao_Dto.User;
using hao_Common.Response.Extensions;
using System;
using System.Threading.Tasks;

namespace hao_User.Api.Controllers
{
    [ApiController]
    [Route("api/role")]
    [Authorize]
    public class RoleController : ControllerBase
    {
        private readonly IRoleService _roleService;
        
        public RoleController(IRoleService roleService)
        {
            _roleService = roleService;
        }
        
        /// <summary>
        /// 获取所有角色（支持分页）
        /// </summary>
        [HttpGet("list")]
        public async Task<IActionResult> GetAllRoles(
            [FromQuery] int? pageNumber = null,
            [FromQuery] int? pageSize = null,
            [FromQuery] string? keyword = null,
            [FromQuery] string? orderBy = null,
            [FromQuery] bool? isDescending = null)
        {
            try
            {
                // 如果没有传递任何分页参数，使用原有逻辑返回所有数据
                if (!pageNumber.HasValue && !pageSize.HasValue)
                {
                    var allRoles = await _roleService.GetAllRolesAsync();
                    return this.SuccessResult(allRoles, "获取角色列表成功");
                }
                
                // 有分页参数时，使用分页查询
                var queryDto = new RolePagedQueryDto
                {
                    PageNumber = pageNumber ?? 1,
                    PageSize = pageSize ?? 10,
                    Keyword = keyword,
                    OrderBy = orderBy ?? "Id",
                    IsDescending = isDescending ?? false
                };
                
                var (roles, totalCount) = await _roleService.GetRolesPagedAsync(queryDto);
                return this.PagedResult(roles, queryDto.PageNumber, queryDto.PageSize, totalCount, "获取角色列表成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"获取角色列表失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 根据ID获取角色
        /// </summary>
        [HttpGet("getRoleById/{roleId}")]
        public async Task<IActionResult> GetRoleById(Guid roleId)
        {
            try
            {
                var role = await _roleService.GetRoleByIdAsync(roleId);
                if (role == null)
                {
                    return this.NotFoundResult("角色不存在");
                }
                return this.SuccessResult(role, "获取角色成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"获取角色失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 创建角色
        /// </summary>
        [HttpPost("createRole")]
        public async Task<IActionResult> CreateRole([FromBody] CreateRoleDto createRoleDto)
        {
            try
            {
                var role = await _roleService.CreateRoleAsync(createRoleDto);
                return this.SuccessResult(role, "创建角色成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"创建角色失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 更新角色
        /// </summary>
        [HttpPut("update/{roleId}")]
        public async Task<IActionResult> UpdateRole(Guid roleId, [FromBody] UpdateRoleDto updateRoleDto)
        {
            try
            {
                var role = await _roleService.UpdateRoleAsync(roleId, updateRoleDto);
                if (role == null)
                {
                    return this.NotFoundResult("角色不存在");
                }
                return this.SuccessResult(role, "更新角色成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"更新角色失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 删除角色
        /// </summary>
        [HttpDelete("del/{roleId}")]
        public async Task<IActionResult> DeleteRole(Guid roleId)
        {
            try
            {
                await _roleService.DeleteRoleAsync(roleId);
                return this.SuccessResult<object>(null, "删除角色成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"删除角色失败：{ex.Message}");
            }
        }
    }
}